package com.korion.android.devicedemon

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import com.korion.android.devicedemon.core.SmsDemonService
import com.korion.android.devicedemon.core.SmsUtils

class MainActivity : AppCompatActivity(), View.OnClickListener{

    companion object {
        private const val TAG = "MainActivity"
    }

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.d(TAG, "onServiceConnected")
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Log.d(TAG, "onServiceDisconnected")
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        startSmsService()
        SmsUtils.checkSmsPermission(this, SmsUtils.SMS_RECEIVE_PERMISSION_CODE
                or SmsUtils.SMS_SEND_PERMISSION_CODE
                or SmsUtils.SMS_READ_PERMISSION_CODE, true)

    }

    private fun startSmsService() {
        val intent = Intent(this, SmsDemonService::class.java).apply {
            this.putExtra(SmsDemonService.KEY_CMD, SmsDemonService.CMD_START_FOREGROUND)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
        bindService(intent, serviceConnection, 0)
    }

    private fun stopSmsService() {
        val intent = Intent(this, SmsDemonService::class.java).apply {
            this.putExtra(SmsDemonService.KEY_CMD, SmsDemonService.CMD_STOP_SERVICE)
        }
        startService(intent)
        unbindService(serviceConnection)
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.btn_startService -> {
                startSmsService()
            }
            R.id.btn_stopService -> {
                stopSmsService()
            }
            R.id.btn_smsTest -> {
                Intent(this, SmsTestActivity::class.java).run {
                    startActivity(this)
                }
            }
            R.id.btn_pushTest -> {
                Intent(this, PushActivity::class.java).run {
                    startActivity(this)
                }
            }
        }

    }


}